#!/usr/bin/env python

from mercurial.i18n import _
from mercurial.node import short
from mercurial import cmdutil, templater, util
import re, time
import urllib2              
import urllib

def create_opener(ui):
	baseurl  =  ui.config('mingle', 'baseurl', default=None, untrusted=False)
	username =  ui.config('mingle', 'username', default=None, untrusted=False)
	password =  ui.config('mingle', 'password', default=None, untrusted=False)
	password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
	password_mgr.add_password(None, baseurl, username, password)
	handler = urllib2.HTTPBasicAuthHandler(password_mgr)
	opener = urllib2.build_opener(handler, urllib2.HTTPSHandler)
	return opener

def story(ctx):
	m = re.search('.*#([0-9]+).*', ctx.description())  
	if (m == None):
	    return None
	else:	
	    return m.group(1)

def story_id(ui, storyCard):
	baseurl = ui.config('mingle', 'baseurl', default=None, untrusted=False) 
	opener = create_opener(ui)	
	request = urllib2.Request(url(baseurl, storyCard)) 
	res = opener.open(request).read()
	m = re.search('<id type="integer">([0-9]+)</id>', res)
	return m.group(1)
	
def url(baseurl, story):
	return baseurl + '/projects/cruise/cards/' + story + '.xml'

                                                  
def create_comment(ui, storyid, comment):
	baseurl = ui.config('mingle', 'baseurl', default=None, untrusted=False) 
	opener = create_opener(ui)
	params = urllib.urlencode(dict(comment=comment))
	request = urllib2.Request(url(baseurl, storyid), params)
	request.get_method = lambda: 'PUT'
	response = opener.open(request)
	                             
def hook(ui, repo, hooktype, node=None, **kwargs):
	password  =  ui.config('mingle', 'password', default=None, untrusted=False)
	if (password == None):
		return
	ctx = repo[node]
	storyCard = story(ctx)
	if (storyCard == None) :
		return                                    
	try:
		storyid = story_id(ui, storyCard)
		comment =  node + '\n' + ctx.description()
		create_comment(ui, storyid, comment)
		ui.write('Mingle card #' + storyCard +' is updated.\n')
	except:
		ui.write('Failed to update Mingle card #' + storyCard + '\n')
	
	

